package apptoko.com;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import apptoko.com.adapter.ErrorHandler;
import apptoko.com.background.BackgroundTasks;
import apptoko.com.event.Event.GetAccessTokenSuccessEvent;
import apptoko.com.event.Event.LogoutEvent;
import apptoko.com.event.Event.RequestTokenEvent;
import apptoko.com.event.Event.UpdateUserInfoFailEvent;
import apptoko.com.event.Event.UpdateUserInfoSuccessEvent;
import apptoko.com.event.Event.UserInfoFailEvent;
import apptoko.com.event.Event.UserInfoSuccessEvent;
import apptoko.com.model.AccessToken;
import apptoko.com.model.UserInfo;
import apptoko.com.network.ProgressDialogManager;
import apptoko.com.util.Constants;
import apptoko.com.util.Utils;
import apptoko.com.validator.Form;
import apptoko.com.validator.Validate;
import apptoko.com.validator.validator.NotEmptyValidator;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.androidquery.AQuery;
import com.appota.asdk.commons.AccessTokenUtil;
import com.appota.asdk.topup.TopupAPI;
import apptoko.com.R;
import com.devspark.appmsg.AppMsg;
import com.google.analytics.tracking.android.EasyTracker;

import de.greenrobot.event.EventBus;

public class AccountActivity extends SherlockActivity implements OnClickListener{
	
	public static final String KEY_GREEN_TYM = "_green_tym";
	public static final String KEY_PURPLE_TYM = "_purple_tym";
	public static final String KEY_USERNAME = "_user_name";
	private EventBus eventBus;
	private BackgroundTasks bgTask;
	private static final int TOAST_DURATION = 4*1000;
	private static final String KEY_YELLOW_TYM = "_yellow_tym";
	private AQuery aQuery;
	private ProgressDialog pdialog;
	private UserInfo userInfo;
	private Form form;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		setTheme(R.style.Theme_Styled_Home);
		super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.activity_account);
		eventBus = EventBus.getDefault();
		bgTask = new BackgroundTasks(this);
		aQuery = new AQuery(this);
		
		getSupportActionBar().setTitle(R.string.account);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            BitmapDrawable bg = (BitmapDrawable)getResources().getDrawable(R.drawable.action_bar_home);
            bg.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
            getSupportActionBar().setBackgroundDrawable(bg);
        }
		getUserInfo();
		form = new Form();
		pdialog=new ProgressDialog(this);
		pdialog.setCancelable(false);
		pdialog.setMessage(getResources().getString(R.string.loading));
		Validate fullnameValidate = new Validate(aQuery.id(R.id.acc_fullname).getEditText());
		fullnameValidate.addValidator(new NotEmptyValidator(this));
		Validate passValidate = new Validate(aQuery.id(R.id.currentPassword).getEditText());
		passValidate.addValidator(new NotEmptyValidator(this));
		form.addValidates(passValidate);
		form.addValidates(fullnameValidate);
		EasyTracker.getInstance().setContext(this);
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		eventBus.register(this);
		com.facebook.AppEventsLogger.activateApp(this, getResources().getString(R.string.fb_app_id));
	}
	
	private void getUserInfo(){
		setSupportProgressBarIndeterminateVisibility(true);
		String accessToken = Utils.getStaticAccessToken(this);
		Log.e("", "accessToken "+accessToken);
		if(accessToken!="3de71f9e84a325bbfb86466c15b40b1e"){
			bgTask.getUserInfo(accessToken);
		}
	}
	
	//get user info success
	public void onEventMainThread(UserInfoSuccessEvent event){
		userInfo = event.getUser();
		aQuery.id(R.id.acc_avatar).image(userInfo.getAvatarUr(), false, true, 0, R.drawable.ic_launcher);
		aQuery.id(R.id.acc_username).text(userInfo.getUserName().toUpperCase(Locale.getDefault()));
		aQuery.id(R.id.green_tym).text(String.valueOf(userInfo.getGreenTym()));
		aQuery.id(R.id.purple_tym).text(String.valueOf(userInfo.getPurpleTym()));
		aQuery.id(R.id.yellow_tym).text(String.valueOf(userInfo.getYellowTym()));
		aQuery.id(R.id.acc_fullname).text(userInfo.getFullName());
		aQuery.id(R.id.acc_email).text(userInfo.getEmail());
		aQuery.id(R.id.acc_dob).text(userInfo.getBirthday());
		aQuery.id(R.id.acc_gender).text(userInfo.getGender());
		String gender=userInfo.getGender();
		Log.e("gender","gender: "+gender);
		aQuery.id(R.id.acc_gender).setSelection(gender.equalsIgnoreCase("male")?0:1).visibility(View.VISIBLE);
		aQuery.id(R.id.currentPasswordLayout).visibility(View.VISIBLE);
		aQuery.id(R.id.btn_update_profile).visibility(View.VISIBLE).clicked(this);
		aQuery.id(R.id.btn_change_pass).clicked(this);
		aQuery.id(R.id.btn_add_tym).clicked(this);
		aQuery.id(R.id.btn_logout).clicked(this);
		setSupportProgressBarIndeterminateVisibility(false);
	}
	
	//get user info fail
	public void onEventMainThread(UserInfoFailEvent failEvent){
		Log.e("", "getuser info fail "+ failEvent.getErrorCode());
		ErrorHandler.getInstance().setContext(this).handleError(failEvent.getErrorCode());
		aQuery.id(R.id.btn_change_pass).enabled(false);
		aQuery.id(R.id.btn_add_tym).enabled(false);
		aQuery.id(R.id.btn_logout).enabled(false);
		setSupportProgressBarIndeterminateVisibility(false);
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		EasyTracker.getInstance().activityStop(this);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		EasyTracker.getInstance().activityStart(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_change_pass:
			EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.EVENT_ACTION, "button-change_password", Long.valueOf(20));
			Intent cp = new Intent(this, ChangePasswordActivity.class);
			cp.putExtra("uid", (int)userInfo.userId);
			startActivity(cp);
			break;
		case R.id.btn_add_tym:
//			EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.EVENT_ACTION, "button-tym", Long.valueOf(20));
//			Intent i = new Intent(this, PaymentActivity.class);
//			Bundle bundle = new Bundle();
//			bundle.putString(KEY_USERNAME, userInfo.getUserName());
//			bundle.putInt(KEY_GREEN_TYM, userInfo.getGreenTym());
//			bundle.putInt(KEY_PURPLE_TYM, userInfo.getPurpleTym());
//			bundle.putInt(KEY_YELLOW_TYM, userInfo.getYellowTym());
//			i.putExtras(bundle);
//			startActivity(i);
			List<String> scopes = new ArrayList<String>();
			scopes.add("user.info");
			scopes.add("user.email");
			TopupAPI.getInstance().setContext(this).topupTYM(scopes, userInfo.getUserName());
			break;
		case R.id.btn_logout:
			EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.EVENT_ACTION, "button-logout", Long.valueOf(20));
			pdialog = ProgressDialogManager.showProgressDialog(this, R.string.logout_ing);
			String accessToken = Utils.getStaticAccessToken(this);
			bgTask.logOut(accessToken);
			break;
		case R.id.btn_update_profile:
			if(form.validate()){
				pdialog.show();
				Date date=new Date();
				bgTask.updateProfile(Utils.getStaticAccessToken(this), userInfo.userId,(date.getTime()) , aQuery.id(R.id.currentPassword).getText().toString(), aQuery.id(R.id.acc_fullname).getText().toString(), aQuery.id(R.id.acc_gender).getSpinner().getSelectedItem().toString().toLowerCase(Locale.US));
			}
		}
	}
	public void onEventMainThread(UpdateUserInfoFailEvent event){
		if(pdialog!=null&&pdialog.isShowing()){
			pdialog.dismiss();
			AppMsg.makeText(this, event.error_code.length()<4?getResources().getString(R.string.error)+"("+event.error_code+")":event.error_code, AppMsg.STYLE_ALERT, null).show();
		}
	}
	public void onEventMainThread(UpdateUserInfoSuccessEvent event){
		if(pdialog!=null&&pdialog.isShowing()){
			pdialog.dismiss();
			AppMsg.makeText(this, getResources().getString(R.string.update_profile_success), AppMsg.STYLE_INFO, null).show();
		}
	}
	//log out success
	public void onEventMainThread(LogoutEvent event){
		if(event.isSuccess()){
			AccessTokenUtil.getInstance().init(this).saveAccessTokenStr("3de71f9e84a325bbfb86466c15b40b1e");
			((AppStoreVnApplication)getApplication()).setAccessToken("3de71f9e84a325bbfb86466c15b40b1e");
			((AppStoreVnApplication) getApplication()).setLogin(false);
			getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE).edit().putBoolean(Constants.LOGIN, false).commit();
//			bgTask.getRequestToken();
			EventBus.getDefault().post(new GetAccessTokenSuccessEvent(new AccessToken()));
		} else {
			AppMsg msg = AppMsg.makeText(this, getResources().getString(R.string.error), AppMsg.STYLE_ALERT, null);
			msg.setLayoutGravity(Gravity.CENTER);
			msg.setDuration(TOAST_DURATION);
			msg.show();
		}
//		Intent i = new Intent(AccountActivity.this, LoginActivity.class);
//		startActivity(i);
//		finish();
	}
	
	public void onEventMainThread(RequestTokenEvent event){
		if(TextUtils.isEmpty(event.getRequestToken())){
			AppMsg.makeText(this, R.string.error, AppMsg.STYLE_ALERT, null).show();
		} else {
			bgTask.getAccessToken(event.getRequestToken());
		}
	}
	
	public void onEventMainThread(GetAccessTokenSuccessEvent event){
		
		if(pdialog != null){
			pdialog.dismiss();
		}
//		AccessToken accessToken = event.getAt();
		((AppStoreVnApplication) getApplication()).setAccessToken("3de71f9e84a325bbfb86466c15b40b1e");
		((AppStoreVnApplication) getApplication()).setCountryCode("en");
		getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE).edit().putString("atg", "3de71f9e84a325bbfb86466c15b40b1e").commit();
//		editor.putString(Constants.REFRESH_TOKEN, accessToken.getRefreshToken());
		//editor.putString(Constants.EXPIRE, accessToken.getExpiresIn());
		AccessTokenUtil.getInstance().init(this).saveAccessTokenStr("3de71f9e84a325bbfb86466c15b40b1e");
		AccessTokenUtil.getInstance().init(this).saveAccessTokenExpires("");
		Intent i = new Intent(AccountActivity.this, LoginActivity.class);
		i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(i);
		finish();
	}
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		//setResult(RESULT_OK);
		super.onBackPressed();
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		eventBus.unregister(this);
	}
}
